#include "../common.h"
#include "timer.h"

//---------算法第一部分，预处理---------
#ifdef OPENCV2
void part1(Stream &stream, Mat &frame,CudaMem &binary) {
    registerPageLocked(frame);
    GpuMat frame_gpu;
    stream.enqueueUpload(frame, frame_gpu);
    GpuMat blur_gpu, buf_gpu;
    GaussianBlur(frame_gpu, blur_gpu, Size(11, 11), buf_gpu, 1.5, 0, BORDER_DEFAULT, -1, stream);
    GpuMat gray_gpu;
    cvtColor(blur_gpu, gray_gpu, CV_BGR2GRAY, 0, stream);
    GpuMat hist_gpu,hist_graph;
    equalizeHist(gray_gpu, hist_gpu,hist_graph,buf_gpu, stream);
    GpuMat binary_gpu;
    threshold(hist_gpu, binary_gpu, 120, 255, THRESH_BINARY, stream);
    stream.enqueueDownload(binary_gpu, binary);
}
#elif defined(OPENCV3)
void part1(Stream &stream, Mat &frame,HostMem &binary){
    GpuMat frame_gpu;
    frame_gpu.upload(frame,stream);
    GpuMat blur_gpu,buf_gpu;
    Ptr<cuda::Filter> gauss = cuda::createGaussianFilter(frame_gpu.type(), -1, Size(11, 11), 1.5);
    gauss->apply(frame_gpu,blur_gpu,stream);
    GpuMat gray_gpu;
    cvtColor(blur_gpu,gray_gpu,CV_BGR2GRAY,0,stream);
    GpuMat hist_gpu;
    equalizeHist(gray_gpu,hist_gpu,stream);
    GpuMat binary_gpu;
    threshold(hist_gpu,binary_gpu,120,255,THRESH_BINARY,stream);
    binary_gpu.download(binary,stream);
}
#endif


int main(){
    if(getCudaEnabledDeviceCount()==0){
        cerr<<"此OpenCV编译的时候没有启用CUDA模块"<<endl;
        return -1;
    }

    VideoCapture capture("../../Stream/data.avi");
    if(!capture.isOpened()){
        cerr<<"打开视频失败"<<endl;
    }

    Stream stream;
    Mat frame,next_frame;
    capture>>frame;
    Timer timer;
#ifdef OPENCV2
    CudaMem binary(frame.size(),CV_8UC1);
#elif defined(OPENCV3)
    HostMem binary(frame.size(),CV_8UC1);
#endif
    part1(stream,frame,binary);
    stream.waitForCompletion();
    timer.log();
    imshow("binary",binary.createMatHeader());
    waitKey(0);
    while (true){
        capture>>frame;
        if(frame.empty()){
            break;
        }
        imshow("frame",frame);
        waitKey(24);

    }
}